package cn.wx.org.service.impl;


import cn.wx.basic.service.impl.BaseServiceImpl;
import cn.wx.basic.util.Md5Utils;
import cn.wx.basic.util.PageList;
import cn.wx.basic.util.StrUtils;
import cn.wx.org.domain.Employee;
import cn.wx.org.mapper.EmployeeMapper;
import cn.wx.org.query.EmployeeQuery;
import cn.wx.org.service.IEmployeeService;
import cn.wx.user.domain.Logininfo;
import cn.wx.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service

public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {

        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(salt+employee.getPassword());
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());

        employeeMapper.save(employee); //返回自增主键id

        //保存中间表
        employeeMapper.saveEmployeRole(employee.getId(),employee.getRole_id());

    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }


    @Override
    public void remove(Long id) {
        //先删除t_employee_role
        employeeMapper.removeEmployeRole(id);
        //在删除emp
        employeeMapper.remove(id);
    }

    @Override
    public void update(Employee employee) {


        //根据id删除t_employee_role
        employeeMapper.removeEmployeRole(employee.getId());

        //在添加一波
        employeeMapper.saveEmployeRole(employee.getId(),employee.getRole_id());

            //更新自己
        employeeMapper.update(employee
        );
    }

    @Override
    public List<Employee> findListEmp(Long shopid) {
        return employeeMapper.findListEmp(shopid);
    }
}
